﻿package net.wangit.framework.expression;

import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;
/**
 * RequestSession表达式
 * @author watson
 *
 */
public class Request2SessionExpression {

	private static final String PREFIX = "$RS{";
	private static final String SUFFIX = "}";

	public Request2SessionExpression() {
	}

	public static final String resolve(ActionContext ac, String expression) {
		return resolve(ac, expression, "", true);
	}

	protected static final String resolve(ActionContext ac, String expression,
			String defaultValue, boolean emptyValid) {
		if (Checker.isEmpty(expression))
			return expression;
		StringBuffer result = new StringBuffer();
		String attribute;
		while ((attribute = StringUtil.find(expression,
				Request2SessionExpression.PREFIX,
				Request2SessionExpression.SUFFIX)) != null) {
			int index = expression.indexOf((new StringBuilder(
					Request2SessionExpression.PREFIX)).append(attribute)
					.append(Request2SessionExpression.SUFFIX).toString());
			result.append(expression.substring(0, index)).append(
					getValue(ac, attribute, defaultValue, emptyValid));
			expression = expression.substring(index + attribute.length()
					+ Request2SessionExpression.PREFIX.length()
					+ Request2SessionExpression.SUFFIX.length());
		}
		result.append(expression);
		return result.toString();
	}

	private static String getValue(ActionContext ac, String attribute,
			String defaultValue, boolean emptyValid) {
		String attributes[] = attribute.split(",");
		if (attributes.length > 2 && !Checker.isEmpty(attributes[2]))
			defaultValue = attributes[2];
		if (emptyValid) {
			return ActionContextHelper.getRequest2Session(ac, attributes[0],
					attributes[1], defaultValue);
		} else {
			String value = ActionContextHelper.getRequest2Session(ac,
					attributes[0], attributes[1], null);
			return Checker.isEmpty(value) ? defaultValue : value;
		}
	}
}
